import json

from fastapi import APIRouter, HTTPException, UploadFile, Form, File, Query
from db.Do import we_library, Album, BaseReq, AlbumFolders
from web_api import file_util
import os
import config
import shutil
import datetime
import aiofiles
from pathlib import Path

router = APIRouter()

base_url = "/album"


@router.post(f"{base_url}/list")
async def get_files(req: BaseReq):
    # 获取非锁定文件夹ID列表
    is_lock_folders = we_library.fetch_all(f"SELECT id FROM album_folders WHERE is_lock = 0 and del_flag = 0",
                                           tuple([]))
    folder_ids = [item['id'] for item in is_lock_folders]
    # 基础查询
    base_query = "SELECT * FROM album"
    conditions = []
    params = []
    # 文件夹筛选
    if req.folder_id != -1:
        conditions.append("folder_id = ?")
        params.append(req.folder_id)
    # 文件类型筛选
    if req.file_type:
        conditions.append("filetype = ?")
        params.append(req.file_type)
    # 文件名关键词筛选
    if req.filename_keyword:
        conditions.append("filename LIKE ?")
        params.append(f'%{req.filename_keyword}%')
    # 锁定状态筛选
    if req.is_lock:
        placeholders = ",".join(["?"] * len(folder_ids))
        conditions.append(f"folder_id IN ({placeholders})")
        params.extend(folder_ids)
    conditions.append("del_flag = ?")
    if req.is_recycle:
        params.append(1)
    else:
        params.append(0)
    # 构建WHERE子句
    if conditions:
        base_query += " WHERE " + " AND ".join(conditions)
    # 添加排序（确保NULL值排在最后）
    base_query += " ORDER BY capture_time DESC"
    # 执行查询获取所有文件（不直接分页）
    all_files = we_library.fetch_all(base_query, tuple(params))
    # 分组数据
    grouped_files = {}
    for file in all_files:
        folder_id = file.get("folder_id")
        filename = file.get("filename")
        folder = we_library.fetch_one(f"SELECT * FROM album_folders WHERE id = {folder_id}")
        if folder["is_external"] == 1:
            file["filepath"] = os.path.join("external", str(folder.get('id')), filename)
        else:
            file["filepath"] = os.path.join(config.source_img_dir, folder.get('folder_name'), filename)
        if file.get("thumb_path") is not None:
            if folder["is_external"] == 1:
                thumb_folder = os.path.join(config.thumb_path_external_dir, folder.get('folder_name'))
            else:
                thumb_folder = os.path.join(config.thumb_path_dir, folder.get('folder_name'))

            if file.get("filetype") == "video":
                file["thumb_path"] = os.path.join(thumb_folder,
                                                  file["thumb_path"])
            if file.get("filetype") == "image":
                file["thumb_path"] = os.path.join(thumb_folder, file["thumb_path"])
        else:
            file["thumb_path"] = None
        # 处理capture_time为null的情况
        capture_time = file.get("capture_time")
        if capture_time is None:
            group_key = "null"
        else:
            # 提取日期部分（格式：YYYY-MM-DD）
            group_key = capture_time.split()[0] if isinstance(capture_time, str) else capture_time
        # 初始化分组列表
        if group_key not in grouped_files:
            grouped_files[group_key] = []
        grouped_files[group_key].append(file)
    # 将分组转换为列表并按日期降序排序
    sorted_groups = sorted(
        [(date, files) for date, files in grouped_files.items() if date != "null"],
        key=lambda x: x[0],
        reverse=True
    )
    # 添加null组到末尾（如果有）
    if "null" in grouped_files:
        sorted_groups.append(("null", grouped_files["null"]))
    # 计算分页参数
    total_groups = len(sorted_groups)
    start_idx = (req.current - 1) * req.size
    end_idx = start_idx + req.size
    # 获取当前页的分组数据
    paginated_groups = sorted_groups[start_idx:end_idx]
    # 转换为前端需要的字典格式
    result_model = {date: files for date, files in paginated_groups}
    return {
        "success": True,
        "current": req.current,
        "size": req.size,
        "total": total_groups,  # 分组总数而非文件总数
        "model": result_model
    }


# 移动文件至指定相册
@router.get(f"{base_url}/update_album")
async def update_album(ids: str, folder_id: int):
    id_list = ids.split(",")
    for id in id_list:
        # 查询文件
        one = we_library.fetch_one(
            "SELECT * FROM album WHERE id = ?;",
            (id,)
        )
        old_folder_id = one.get("folder_id")
        old_folder = we_library.fetch_one(f"SELECT * FROM album_folders WHERE id = {old_folder_id}")

        # 将文件移动至新相册
        old_file_path = os.path.join(config.ROOT_DIR_WIN, config.source_img_dir, old_folder["folder_name"],
                                     one["filename"])
        new_folder = we_library.fetch_one(f"SELECT * FROM album_folders WHERE id = {folder_id}")
        new_file_path = os.path.join(config.ROOT_DIR_WIN, config.source_img_dir, new_folder["folder_name"])
        shutil.move(Path(old_file_path), Path(new_file_path))

        # 将缩略图移动至新相册
        if new_folder["is_external"] == 0:
            old_thumb_path_path = os.path.join(config.ROOT_DIR_WIN, config.thumb_path_dir, old_folder["folder_name"],
                                               one["thumb_path"])
        elif new_folder["is_external"] == 1:
            old_thumb_path_path = os.path.join(config.ROOT_DIR_WIN, config.thumb_path_external_dir,
                                               old_folder["folder_name"],
                                               one["thumb_path"])
        new_thumb_path_path = os.path.join(config.ROOT_DIR_WIN, config.thumb_path_dir, new_folder["folder_name"])
        shutil.move(Path(old_thumb_path_path), Path(new_thumb_path_path))
        # 更新数据库记录
        do_album = Album(
            table_name="album",  # 直接初始化字段值
            id=id,
            folder_id=folder_id,
        )
        we_library.add_or_update(do_album, do_album.table_name)
    return {"success": True, "message": f"操作成功"}


# 删除文件
@router.get(f"{base_url}/del_album")
async def del_album(ids: str):
    id_list = ids.split(",")
    for id in id_list:
        # 删除数据库记录
        we_library.execute_query(f"UPDATE album SET del_flag = 1 WHERE id = {id};")
    return {"success": True, "message": f"删除成功"}


# 还原文件
@router.get(f"{base_url}/restore_album")
async def del_album(ids: str):
    id_list = ids.split(",")
    for id in id_list:
        # 还原数据库记录
        we_library.execute_query(f"UPDATE album SET del_flag = 0 WHERE id = {id};")
    return {"success": True, "message": f"还原成功"}


# 清空回收站
@router.get(f"{base_url}/clear_recycle_bin")
async def clear_recycle_bin():
    # 查询文件
    all_album = we_library.fetch_all(
        "SELECT * FROM album WHERE del_flag = 1;"
    )
    for album in all_album:
        folder_id = album.get("folder_id")
        folder_one = we_library.fetch_one(f"SELECT * FROM album_folders WHERE id = {folder_id}")
        try:
            if folder_one["is_external"] == 0:
                file_path = os.path.join(config.ROOT_DIR_WIN, config.source_img_dir, folder_one["folder_name"],
                                         album["filename"])
                thumb_path = os.path.join(config.ROOT_DIR_WIN, config.thumb_path_dir, folder_one["folder_name"],
                                          album["thumb_path"])
            elif folder_one["is_external"] == 1:
                file_path = os.path.join(folder_one["external_path"], album["filename"])
                thumb_path = os.path.join(config.ROOT_DIR_WIN, config.thumb_path_external_dir,
                                          folder_one["folder_name"],
                                          album["thumb_path"])
            # 删除物理文件
            os.remove(file_path)
            # 删除缩略图
            os.remove(thumb_path)
        except Exception as e:
            print("Error:", e)
    # 删除文件记录
    we_library.execute_query("DELETE FROM album where del_flag = 1;", )
    # 删除相册记录
    we_library.execute_query("DELETE FROM album_folders where del_flag = 1;")
    return {"success": True, "message": f"删除成功"}


# 查询相册列表
@router.get(f"{base_url}/folders")
async def get_folders(id: int, is_lock: int):
    if id == -1:
        # 如果传-1则查询全部
        folder_list = we_library.fetch_all(f"SELECT * FROM album_folders WHERE is_lock = {is_lock} and del_flag = 0")
        for folder in folder_list:
            folder_id = folder.get("id")
            album_count = we_library.fetch_all(
                f"SELECT count(*) FROM album where folder_id = {folder_id} and del_flag = 0")
            folder["file_count"] = album_count[0].get("count(*)")
            album_one = we_library.fetch_one(
                "SELECT * FROM album WHERE filetype = ? and folder_id = ? and del_flag = 0 LIMIT 1;",
                ("image", folder_id,)
            )
            if album_one:
                if album_one.get("thumb_path") is not None:
                    if folder["is_external"] == 1:
                        thumb_folder = os.path.join(config.thumb_path_external_dir, folder.get('folder_name'))
                    else:
                        thumb_folder = os.path.join(config.thumb_path_dir, folder.get('folder_name'))
                    filepath = os.path.join(thumb_folder, album_one.get("thumb_path"))
                    folder["thumb_path"] = filepath
        return folder_list
    else:
        one = we_library.fetch_one(f"SELECT * FROM album_folders WHERE id = {id}")
        return one


# 新增相册
@router.get(f"{base_url}/add_album_folders")
async def add_album_folders(album_name: str, ):
    # 创建目标相册
    target_folder = os.path.join(config.ROOT_DIR_WIN, config.source_img_dir, album_name)
    os.makedirs(target_folder, exist_ok=True)

    # 创建缩略图文件夹
    target_folder = os.path.join(config.ROOT_DIR_WIN, config.thumb_path_dir, album_name)
    os.makedirs(target_folder, exist_ok=True)

    one = we_library.fetch_one(f"SELECT * FROM album_folders WHERE folder_name = ?;", (album_name,))
    if one is None:
        external_path = os.path.join(config.source_img_dir, album_name)
        # 添加文件夹记录
        # 创建 AlbumFolders 实例
        do_folders = AlbumFolders(
            table_name="album_folders",  # 直接初始化字段值
            folder_name=album_name,
            external_path=external_path,
        )
        we_library.add_or_update(do_folders, do_folders.table_name)
    return True


# 修改相册名称
@router.post(f"{base_url}/update_album_folder")
async def update_album_folder(req: BaseReq):
    # 查询相册
    one = we_library.fetch_one(
        "SELECT * FROM album_folders WHERE id = ?;",
        (req.id,)
    )
    # 重命名相册
    old_path = os.path.join(config.ROOT_DIR_WIN, config.source_img_dir, one["folder_name"])
    new_path = os.path.join(config.ROOT_DIR_WIN, config.source_img_dir, req.new_name)
    os.rename(old_path, new_path)
    # 重命名缩略图
    old_thumb_path = os.path.join(config.ROOT_DIR_WIN, config.thumb_path_dir, one["folder_name"])
    new_thumb_path = os.path.join(config.ROOT_DIR_WIN, config.thumb_path_dir, req.new_name)
    os.rename(old_thumb_path, new_thumb_path)
    external_path = os.path.join(config.source_img_dir, req.new_name)
    # 更新数据库记录
    do_folders = AlbumFolders(
        table_name="album_folders",  # 直接初始化字段值
        id=req.id,
        folder_name=req.new_name,
        external_path=external_path,
    )
    we_library.add_or_update(do_folders, do_folders.table_name)
    return {"status": "success", "message": f"修改成功"}


# 锁定相册
@router.get(f"{base_url}/lock_album")
async def lock_album(id: int):
    do_folders = AlbumFolders(
        table_name="album_folders",  # 直接初始化字段值
        id=id,
        is_lock=1
    )
    we_library.add_or_update(do_folders, do_folders.table_name)
    return True


# 解锁相册
@router.get(f"{base_url}/unlock_album")
async def lock_album(id: int):
    do_folders = AlbumFolders(
        table_name="album_folders",  # 直接初始化字段值
        id=id,
        is_lock=0
    )
    we_library.add_or_update(do_folders, do_folders.table_name)
    return True


# 设置锁定密码
@router.get(f"{base_url}/set_lock_password")
async def set_lock_password(password: str):
    file_util.update_value("lock_password", password)
    return True


# 删除相册
@router.get(f"{base_url}/del_album_folder")
async def delete_album_folder(id: int):
    # 查询相册
    one = we_library.fetch_one(
        "SELECT * FROM album_folders WHERE id = ?;",
        (id,)
    )
    # 删除物理文件夹
    folder_path = os.path.join(config.ROOT_DIR_WIN, config.source_img_dir, one["folder_name"])
    if os.path.exists(folder_path):
        shutil.rmtree(folder_path)  # 递归删除整个文件夹
    # 删除缩略图
    if one["is_external"] == 1:
        thumb_path = os.path.join(config.ROOT_DIR_WIN, config.thumb_path_external_dir, one["folder_name"])
    else:
        thumb_path = os.path.join(config.ROOT_DIR_WIN, config.thumb_path_dir, one["folder_name"])
    if os.path.exists(thumb_path):
        shutil.rmtree(thumb_path)
    # 删除文件记录
    we_library.execute_query("DELETE FROM album WHERE folder_id=?;", (id,))
    # 删除相册记录
    we_library.execute_query("DELETE FROM album_folders WHERE id=?;", (id,))
    return {"status": "success", "message": f"已删除"}


# 打开相册文件夹
@router.get(f"{base_url}/open_folder")
async def open_folder(id: int):
    # 查询相册
    one = we_library.fetch_one(
        "SELECT * FROM album_folders WHERE id = ?;",
        (id,)
    )
    if one is None:
        return False
    if one["is_external"] == 0:
        external_path = os.path.join(config.ROOT_DIR_WIN, config.source_img_dir, one["folder_name"])
        external_path = Path(external_path)
    else:
        external_path = one["external_path"]
    # 打开文件夹
    file_util.open_folder(external_path)
    return True


# 判断是否未设置密码
@router.get(f"{base_url}/is_lock_password")
async def is_lock_password():
    if file_util.load_config().get("lock_password") is None:
        return True
    return False


# 设置锁定密码
@router.get(f"{base_url}/set_lock_password")
async def set_lock_password(password: str):
    file_util.update_value("lock_password", password)
    return True


# 重置锁定密码
@router.get(f"{base_url}/reset_lock_password")
async def reset_lock_password(old_password: str, new_password: str):
    if file_util.load_config().get("lock_password") != old_password:
        return False
    file_util.update_value("lock_password", new_password)
    return True


# 访问相册
@router.get(f"{base_url}/unlock")
async def unlock(password: str):
    if file_util.load_config().get("lock_password") == password:
        return True
    return False


# 上传文件
@router.post(f"{base_url}/upload_file")
async def upload_file(file: UploadFile = File(...),
                      folder_id: int = Form(...),
                      folder_name: str = Form(...),
                      last_modified_time: str = Form(...)):
    # 提取纯文件名
    filename = os.path.basename(file.filename)
    # filetype获取
    filetype = file_util.get_file_type(filename)

    # 读取文件内容
    file_read = await file.read()
    # 获取文件大小
    file_size = len(file_read)
    # 初始化元数据变量
    longitude, latitude = None, None
    exif_data = {}

    # 仅当图片文件时尝试提取EXIF，经纬度和文件创建时间
    if filetype == 'image':
        exif_data, capture_time, longitude, latitude = file_util.get_img_info(file_read)
        # 当拍摄时间不存在赋值将前端传过来的文件创建时间
        if capture_time is None:
            capture_time = last_modified_time
    else:
        capture_time = last_modified_time
    # 查询相册是否存在
    if folder_id == -1:
        folder_one = we_library.fetch_one(
            "SELECT * FROM album_folders WHERE folder_name = ?;",
            (folder_name,))
        if folder_one is not None:
            folder_id = folder_one["id"]
        if folder_one is None:
            folders_path = os.path.join(config.ROOT_DIR_WIN, config.source_img_dir, folder_name)
            os.makedirs(folders_path, exist_ok=True)
            external_path = os.path.join(config.source_img_dir, folder_name)
            do_album_folders = AlbumFolders(
                table_name="album_folders",
                folder_name=folder_name,
                external_path=external_path,
            )
            folder_id = we_library.add_or_update(do_album_folders, do_album_folders.table_name)

    else:
        folder_one = we_library.fetch_one(
            "SELECT * FROM album_folders WHERE id = ?;",
            (folder_id,)
        )
        folder_name = folder_one["folder_name"]

    if folder_one["is_external"] == 0:
        access_path = os.path.join(config.ROOT_DIR_WIN, config.source_img_dir, folder_name, filename)
        folder_path = os.path.join(config.ROOT_DIR_WIN, config.thumb_path_dir, folder_name)
    else:
        folder_path = os.path.join(config.ROOT_DIR_WIN, config.thumb_path_external_dir, folder_name)
        access_path = os.path.join(folder_one["external_path"], filename)
    # 分块写入文件（适合大文件）
    await file.seek(0)  # 重置文件指针到开头
    with open(access_path, "wb") as buffer:
        while content := await file.read(1024 * 1024):  # 每次读取1MB
            buffer.write(content)
    duration = "00:00:00"
    thumb_path = None
    if filetype in ['image', 'video']:
        # 生成缩略图
        thumb_path = await file_util.thumbnail(filetype, access_path, folder_path, filename)
    if filetype == 'video':
        # 获取video时长
        duration = file_util.get_video_duration(access_path)
    if filetype == 'audio':
        # 获取audio时长
        duration = file_util.get_audio_duration(access_path)
    # 序列化元数据
    json_str = json.dumps(exif_data, indent=4, ensure_ascii=False)

    # 插入数据库记录
    do_files = Album(
        table_name="album",  # 直接初始化字段值
        folder_id=folder_id,
        filename=filename,
        filepath=str(access_path),
        filesize=file_size,
        duration=duration,
        filetype=filetype,
        longitude=longitude,
        latitude=latitude,
        capture_time=capture_time,
        metadata=str(json_str),
        thumb_path=thumb_path,
    )
    we_library.add_or_update(do_files, do_files.table_name)
    return {
        "success": True,
        "message": f"操作成功"
    }


# 外部文件导入
@router.post(f"{base_url}/external_file")
async def external_file(req: BaseReq):
    external_path = req.external_path
    # 验证路径是否存在
    if not os.path.exists(external_path):
        raise HTTPException(status_code=404, detail="指定的路径不存在")

    # 验证路径是否为文件夹
    if not os.path.isdir(external_path):
        raise HTTPException(external_path=400, detail="提供的路径不是一个文件夹")

    # 获取文件夹名称 (路径的最后一部分)
    folder_name = os.path.basename(os.path.normpath(external_path))

    folder_one = we_library.fetch_one(
        "SELECT * FROM album_folders WHERE external_path = ? Limit 1;",
        (external_path,)
    )
    if folder_one is not None:
        folder_id = folder_one["id"]
    else:
        do_album_folders = AlbumFolders(
            table_name="album_folders",
            folder_name=folder_name,
            external_path=external_path,
            is_external=1
        )
        folder_id = we_library.add_or_update(do_album_folders, do_album_folders.table_name)
    for entry in os.listdir(external_path):
        entry_path = os.path.join(external_path, entry)
        access_path = str(entry_path)
        folder_one = we_library.fetch_one(
            "SELECT * FROM album WHERE folder_id = ? and filepath = ? Limit 1;",
            (folder_id, access_path,)
        )
        if folder_one is not None:
            continue
        if os.path.isfile(entry_path):
            # 提取纯文件名
            filename = os.path.basename(entry)
            # filetype获取
            filetype = file_util.get_file_type(filename)
            # 读取文件内容
            async with aiofiles.open(entry_path, 'rb') as f:
                file_read = await f.read()
            # 获取文件大小
            file_size = len(file_read)
            # 初始化元数据变量
            longitude, latitude = None, None
            exif_data = {}
            # 仅当图片文件时尝试提取EXIF，经纬度和文件创建时间
            if filetype == 'image':
                exif_data, capture_time, longitude, latitude = file_util.get_img_info(file_read)
                # # 当拍摄时间不存在赋值将前端传过来的文件创建时间
                if capture_time is None:
                    # capture_time = last_modified_time
                    capture_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            else:
                capture_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            duration = "00:00:00"
            thumb_path = None
            if filetype in ['image', 'video']:
                folder_path = os.path.join(config.ROOT_DIR_WIN, config.thumb_path_external_dir, folder_name)
                # 生成缩略图
                thumb_path = await file_util.thumbnail(filetype, access_path, folder_path, filename, )
            if filetype == 'video':
                # 获取video时长
                duration = file_util.get_video_duration(access_path)
            if filetype == 'audio':
                # 获取audio时长
                duration = file_util.get_audio_duration(access_path)
            # 序列化元数据
            json_str = json.dumps(exif_data, indent=4, ensure_ascii=False)
            # 插入数据库记录
            do_files = Album(
                table_name="album",  # 直接初始化字段值
                folder_id=folder_id,
                filename=filename,
                filepath=access_path,
                filesize=file_size,
                duration=duration,
                filetype=filetype,
                longitude=longitude,
                latitude=latitude,
                capture_time=capture_time,
                metadata=str(json_str),
                thumb_path=thumb_path,
            )
            we_library.add_or_update(do_files, do_files.table_name)
    return {
        "success": True,
        "message": f"操作成功"
    }


# 获取地图标记数据
@router.get(f"{base_url}/map/locations")
def get_map_locations():
    try:
        # 精度位数	物理范围	适用场景
        # 1位小数	≈10km	城市级别聚合（推荐方案）
        # 2位小数	≈1km	城区/街区级别
        # 3位小数	≈100m	精确地标建筑
        # 4位小数	≈11m（原始值）	高精度定位（不适合城市聚合）
        precision = 1
        query = f"""
                SELECT ROUND(longitude, {precision}) AS longitude, -- 关键修改
                       ROUND(latitude, {precision})  AS latitude,  -- 关键修改
                       COUNT(id) AS count
                FROM album
                WHERE
                    del_flag = 0
                  AND longitude IS NOT NULL
                  AND latitude IS NOT NULL
                GROUP BY ROUND(longitude, {precision}), ROUND(latitude, {precision}) 
                """

        results = we_library.fetch_all(query)
        locations = [
            {
                "longitude": row["longitude"],
                "latitude": row["latitude"],
                "count": row["count"]
            }
            for row in results
        ]
        return locations
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


# 获取特定位置的图片
@router.get(f"{base_url}/map/location/photos")
def get_location_photos(longitude: float,
                        latitude: float,
                        page: int = Query(1, gt=0),  # 页码，从1开始，大于0
                        page_size: int = Query(10, gt=0)  # 每页数量，大于0
                        ):
    precision = 1
    # 构建查询SQL
    query = f"""
            SELECT *
            FROM album
            WHERE del_flag = 0
              AND ROUND(longitude, {precision}) = ROUND(?, {precision})
              AND ROUND(latitude, {precision}) = ROUND(?, {precision})
            """
    params = [longitude, latitude]
    # 获取总记录数
    total = we_library.fetch_count(query, tuple(params))
    # 分页查询
    query += " LIMIT ? OFFSET ?"
    params.extend([page_size, (page - 1) * page_size])
    photos = we_library.fetch_all(query, params)

    # 转换日期格式为ISO格式
    for photo in photos:
        if "create_time" in photo and photo["create_time"]:
            photo["create_time"] = datetime.datetime.strptime(photo["create_time"], "%Y-%m-%d %H:%M:%S").isoformat()
        if "file_create_time" in photo and photo["file_create_time"]:
            photo["file_create_time"] = datetime.datetime.strptime(photo["file_create_time"],
                                                                   "%Y-%m-%d %H:%M:%S").isoformat()
    for file in photos:
        folder_id = file.get("folder_id")
        filename = file.get("filename")
        folder = we_library.fetch_one(f"SELECT * FROM album_folders WHERE id = {folder_id}")
        if folder["is_external"] == 1:
            file["filepath"] = os.path.join("external", str(folder.get('id')), filename)
        else:
            file["filepath"] = os.path.join(config.source_img_dir, folder.get('folder_name'), filename)
        if file.get("thumb_path") is not None:
            if folder["is_external"] == 1:
                thumb_folder = os.path.join(config.thumb_path_external_dir, folder.get('folder_name'))
            else:
                thumb_folder = os.path.join(config.thumb_path_dir, folder.get('folder_name'))

            if file.get("filetype") == "video":
                file["thumb_path"] = os.path.join(thumb_folder,
                                                  file["thumb_path"])
            if file.get("filetype") == "image":
                file["thumb_path"] = os.path.join(thumb_folder, file["thumb_path"])
        else:
            file["thumb_path"] = None
    return {"success": True,
            "photos": photos,
            "total": total, }
